package leetcode.code0279;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	public int numSquares(int n) {
		Integer[] map = new Integer[10001];
		return this.f(n, (int) Math.sqrt(n), map);
	}

	private int f(int n, int max, Integer[] map) {
		if (n == 0) {
			return 0;
		}
		if (map[n] != null) {
			return map[n];
		}
		int ans = Integer.MAX_VALUE;
		int nextn = n - max * max;
		if (nextn >= 0) {
			ans = this.f(nextn, (int) Math.sqrt(nextn), map) + 1;
		}
		if (max - 1 != 0) {
			ans = Math.min(ans, this.f(n, max - 1, map));
		}
		map[n] = ans;
		return ans;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(3, this.numSquares(12));

	}

	@Override
	public void debug2() {
		HelpDebug.compare(2, this.numSquares(13));

	}

	@Override
	public void debug3() {
		HelpDebug.compare(2, this.numSquares(13));
	}

	@Override
	public void debug4() {
		HelpDebug.compare(3, this.numSquares(48));

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

		System.out.println(Math.sqrt(12));

	}

}
